package edu.suda.cxtz.service.impl;

import com.github.dozermapper.core.Mapper;
import edu.suda.cxtz.entity.DictDetail;
import edu.suda.cxtz.repository.DictDetailRepository;
import edu.suda.cxtz.repository.DictRepository;
import edu.suda.cxtz.entity.dto.DictDetailDto;
import edu.suda.cxtz.service.DictDetailService;
import edu.suda.cxtz.utils.DtoEntityUtil;
import edu.suda.cxtz.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class DictDetailServiceImpl implements DictDetailService {

    private final DictRepository dictRepository;
    private final DictDetailRepository dictDetailRepository;
    private final DtoEntityUtil mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DictDetail resources) {
        dictDetailRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DictDetail resources) {
        DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new);
        ValidationUtil.isNull(dictDetail.getId(), "DictDetail", "id", resources.getId());
        resources.setId(dictDetail.getId());
        dictDetailRepository.save(resources);
    }

    @Override
    public List<DictDetailDto> getDictByName(String name) {
        List<DictDetail> dictDetail = dictDetailRepository.findByDictName(name);
        return mapper.trans(dictDetail, DictDetailDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
        dictDetailRepository.deleteById(id);
    }
}